﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Repayment.aspx.cs" Inherits="CRMWeb.Pages.AM.Repayment" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <div style="float: left; width: 100%">
        <input type="hidden" id="hdnbankid1" />
        <input type="hidden" id="hdnbankid2" />
        <table style="width: 100%;">
            <tr>
                <td colspan="4" style="text-align: right;">
                    <span id="lnkbtnSaveRepayment"><a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save'" onclick="SaveRepayment()">Save</a></span>
                    <span id="lnkbtnAddRepayment"><a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="AddRepayment()">Create Repayments</a></span>
                </td>
            </tr>
            <tr>
                <td style="vertical-align: top; width: 100%;">
                    <div class="topform_section">
                        <div class="firstform_section">
                            <div class="ftitle">REPAYMENTS</div>
                            <div class="fitem">
                                <label>Repayment:</label>
                                <input id="txtRepayment" style="width: 150px;" value="0" class="easyui-numberbox" data-options="min:0,precision:2,formatter:parseValue" name="Repayment" />
                            </div>
                            <div class="fitem">
                                <label>Payment Frequency:</label>
                                <input class="easyui-combobox" id="txtFreq" style="width: 150px;" name="Freq"
                                    data-options="url:'/WebServices/AM/LoanForm.ashx?method=GetAllPaymentPeriod',
				                                    valueField:'PaymentPeriod',
				                                    textField:'PaymentPeriod',
                                                    editable:false,
				                                    panelHeight:'auto'" />
                            </div>
                            <div class="fitem">
                                <label>Interest Method:</label>
                                <select id="txtMethod" class="easyui-combobox" data-options="panelHeight:'auto',editable:false" name="Method" style="width: 150px;">
                                    <option value="Simple">Simple</option>
                                    <option value="Compound">Compound</option>
                                </select>
                            </div>
                            <div class="fitem">
                                <label>Next Payment Date:</label>
                                <input id="txtNextPaymentDate" name="NextPaymentDate" class="easyui-datebox" data-options="formatter:formatLoanDate" style="width: 90px;" />
                            </div>
                            <div class="fitem">
                                <label>Total Paid:</label>
                                <input id="txtTotalPaid" style="width: 150px;" value="0" class="easyui-numberbox" data-options="min:0,precision:2,formatter:parseValue" name="TotalPaid" />
                            </div>
                            <div class="fitem">
                                <label>Contractual Maturity:</label>
                                <input id="txtContractualMaturity" name="ContractualMaturity" class="easyui-datebox" data-options="formatter:formatLoanDate" style="width: 90px;" />
                            </div>
                            <div class="fitem">
                                <label>Projected Maturity:</label>
                                <input id="txtProjectedMaturity" name="ProjectedMaturity" class="easyui-datebox" data-options="formatter:formatLoanDate" style="width: 90px;" />
                            </div>
                            <div class="fitem">
                                <label>Residual (Balloon):</label>
                                <input id="txtResidual" style="width: 150px;" value="0" class="easyui-numberbox" data-options="min:0,precision:2,formatter:parseValue" name="Residual" />
                            </div>
                            <div class="fitem">
                                <label>Balance:</label>
                                <input id="txtBalance" style="width: 150px;" value="0" class="easyui-numberbox" data-options="min:0,precision:2,formatter:parseValue" name="Balance" />
                            </div>
                            <div class="fitem">
                                <label>Daily Rate:</label>
                                <input id="txtDailyRate" style="width: 150px;" value="0" class="easyui-numberbox" data-options="min:0,precision:2,formatter:parseValue" name="DailyRate" />
                            </div>
                        </div>
                        <div class="firstform_section">
                            <div class="ftitle">ARREARS</div>
                            <div class="fitem">
                                <label>Num of Dishonours:</label>
                                <input id="txtNumofDishonours" style="width: 110px;" class="easyui-numberbox" name="NumofDishonours" />
                            </div>
                            <div class="fitem">
                                <label>Total Arrears:</label>
                                <input id="txtTotalArrears" style="width: 110px;" value="0" class="easyui-numberbox" data-options="min:0,precision:2,formatter:parseValue" name="TotalArrears" />
                            </div>
                            <div class="fitem">
                                <label>Days Overdue:</label>
                                <input id="txtDaysOverdue" style="width: 110px;" class="easyui-numberbox" name="DaysOverdue" />
                            </div>
                            <div class="fitem">
                                <label>Date of Default:</label>
                                <input id="txtDateofDefault" name="DateofDefault" class="easyui-datebox" data-options="formatter:formatLoanDate" style="width: 90px;" />
                            </div>
                            <div class="ftitle">
                                DDR BANK ACCOUNT
                                <span id="lnkbtnEditDDRBank"><a id="abtnEditDDRBank" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-edit'" onclick="">Edit</a></span>
                            </div>
                            <div class="fitem">
                                <label>Account Holder:</label>
                                <input id="txtAccountHolder" style="width: 150px;" class="easyui-validatebox" />
                            </div>
                            <div class="fitem">
                                <label>Bank:</label>
                                <input id="txtBank11" style="width: 150px;" class="easyui-validatebox" />
                            </div>
                            <div class="fitem">
                                <label>BSB:</label>
                                <input id="txtBSB11" style="width: 150px;" class="easyui-validatebox" name="bsb1" maxlength="7" mask="999-999" validationexpression="^\d{3}-\d{3}$" />
                            </div>
                            <div class="fitem">
                                <label>Account Number:</label>
                                <input id="txtAccountNo11" style="width: 150px;" class="easyui-validatebox" maxlength="9" />
                            </div>
                        </div>

                        <div class="firstform_section">
                            <table id="dgPaymentSchedule" title="PAYMENT SCHEDULE"   style="width: auto; height: 300px"
                                data-options="pageSize:10 " toolbar="#toolbarPaymentSchedule"
                                rownumbers="true" fitcolumns="true" singleselect="true">
                                <thead>
                                    <tr>
                                        <th field="date" width="60" data-options="formatter:formatLoanDate">Date</th>
                                        <th field="day" width="50">Day</th>
                                        <th field="amount" width="50">Amount</th>
                                    </tr>
                                </thead>
                            </table>
                            <div id="toolbarPaymentSchedule">
                                <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-edit" plain="true" onclick="PaymentSchedule()">Edit</a>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        </table>
    </div>

    <script type="text/javascript">
        function PaymentSchedule() {
            myWindow = window.open("EditPaymentSchedule.aspx?LoanID=" + getQuerystring('LoanID', '') + "&Theme=metro-red", "", "width=700,height=550,left=300,top=60,resize=no,scrollbars=yes");
            myWindow.focus();
        }
        //function CancelEditDDRBank() {
        //    $('#txtAccountHolder').attr('readonly', true);
        //    $('#txtBank11').attr('readonly', true);
        //    $('#txtBSB11').attr('disabled', true);
        //    $('#txtAccountNo11').attr('readonly', true);
        //}
        //function EditDDRBank() {
        //    $('#txtAccountHolder').attr('readonly', false);
        //    $('#txtBank11').attr('readonly', false);
        //    $('#txtBSB11').attr('disabled', false);
        //    $('#txtAccountNo11').attr('readonly', false);
        //}
        function formatLoanDate(value, row) {
            if (value == null)
                return value;
            var date = new Date(value);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var d = date.getDate();
            return (d < 10 ? ('0' + d) : d) + '/' + (m < 10 ? ('0' + m) : m) + '/' + y;
        }
        function parseValue(value) {
            return parseFloat(value);
        }
        $(document).ready(function () {
            $('#abtnEditDDRBank').attr('disabled', true);
            $('#lnkbtnSaveRepayment').hide();
            $('#lnkbtnAddRepayment').show();
            $('input[name="bsb"]').mask("999-999");
            $('input[name="bsb1"]').mask("999-999");
           // DisplayRepayment();
            setHeight();

            $('#dgPaymentSchedule').datagrid({
                data: []
            });
        });

        function getpaymentScgedule() {
            $('#dgPaymentSchedule').datagrid({
                url:'/WebServices/AM/Repayment.ashx?method=RePaymentScheduleSelect&LoanID='+getQuerystring('LoanID', '')
            });
        }

        /*Add New Repayment*/
        function AddRepayment() {
            /*Get Text Value*/
            var AccountHolder2 = $('#txtAccountHolder').val();
            var BankName1 = $('#txtBank11').val();
            var BSB1 = $('#txtBSB11').val();
            var AccountNo1 = $('#txtAccountNo11').val();

            /*Get Numeric Value*/
            var Repayment1 = $("#txtRepayment").numberbox('getValue');
            var TotalPaid = $("#txtTotalPaid").numberbox('getValue');
            var Residual = $("#txtResidual").numberbox('getValue');
            var Balance = $("#txtBalance").numberbox('getValue');
            var DailyRate = $("#txtDailyRate").numberbox('getValue');
            var NumofDishonours = $("#txtNumofDishonours").numberbox('getValue');
            var TotalArrears = $("#txtTotalArrears").numberbox('getValue');
            var DaysOverdue = $("#txtDaysOverdue").numberbox('getValue');
            var Method1 = $("#txtMethod").combobox('getValue');
            var Freq = $("#txtFreq").combobox('getValue');

            /*Get Date Value*/
            var NextPaymentDate = $('#txtNextPaymentDate').datebox('getValue');
            if (NextPaymentDate != '')
                NextPaymentDate = DefaultformatLoanDate($('#txtNextPaymentDate').datebox('getValue'));
            var ContractualMaturity = $('#txtContractualMaturity').datebox('getValue');
            if (ContractualMaturity != '')
                ContractualMaturity = DefaultformatLoanDate($('#txtContractualMaturity').datebox('getValue'));
            var ProjectedMaturity = $('#txtProjectedMaturity').datebox('getValue');
            if (ProjectedMaturity != '')
                ProjectedMaturity = DefaultformatLoanDate($('#txtProjectedMaturity').datebox('getValue'));
            var DateofDefault = $('#txtDateofDefault').datebox('getValue');
            if (DateofDefault != '')
                DateofDefault = DefaultformatLoanDate($('#txtDateofDefault').datebox('getValue'));

            /*set value to numeric if it is blank*/
            if (Repayment1 == '')
                Repayment1 = '0.00';
            if (TotalPaid == '')
                TotalPaid = '0.00';
            if (Residual == '')
                Residual = '0.00';
            if (Balance == '')
                Balance = '0.00';
            if (DailyRate == '')
                DailyRate = '0.00';
            if (TotalPaid == '')
                TotalPaid = '0.00';
            if (TotalArrears == '')
                TotalArrears = '0.00';
            if (NumofDishonours == '')
                NumofDishonours = '0';
            if (DaysOverdue == '')
                DaysOverdue = '0';

            // insert record into am_repayments table for 
            $.ajax({
                url: '/WebServices/AM/Repayment.ashx?method=AddRepayment',
                contentType: 'application/json; charset=utf-8',
                data: { "Repayment": Repayment1, "Freq": Freq, "Method1": Method1, "NextPaymentDate": NextPaymentDate, "TotalPaid": TotalPaid, "ContractualMaturity": ContractualMaturity, "ProjectedMaturity": ProjectedMaturity, "Residual": Residual, "Balance": Balance, "DailyRate": DailyRate, 'LoanID': getQuerystring('LoanID', '') },
                success: function (data) {
                }
            });

            // insert record into am_arrears table for 
            $.ajax({
                url: '/WebServices/AM/Repayment.ashx?method=AddArrears',
                contentType: 'application/json; charset=utf-8',
                data: { "NumofDishonours": NumofDishonours, "TotalArrears": TotalArrears, "DaysOverdue": DaysOverdue, "DateofDefault": DateofDefault, 'LoanID': getQuerystring('LoanID', '') },
                success: function (data) {
                }
            });

            // insert record into bank details table for 
            LoanType = "DDR BANK ACCOUNT REPAYMENT";
            $.ajax({
                url: '/WebServices/AM/Repayment.ashx?method=AddBankInfo',
                contentType: 'application/json; charset=utf-8',
                data: { "BankName": BankName1, "AccountNo": AccountNo1, "BSB": BSB1, 'LoanID': getQuerystring('LoanID', ''), "LoanType": LoanType, "AccountHolder": AccountHolder2 },
                success: function (data) {
                    if (data == '1') {
                        $('#abtnEditDDRBank').linkbutton('enable');
                        alert("Insert Data Successfully");
                        $('#pnlRepayment').panel('refresh', 'Repayment.aspx?LoanID=' + getQuerystring('LoanID', ''));
                    }
                }
            });
        }

        /*Display Loan */
        function DisplayRepayment() {

            $.ajax({
                url: '/WebServices/AM/Repayment.ashx?method=SearchRepaymentByLoanID',
                contentType: 'application/json; charset=utf-8',
                data: { 'LoanID': getQuerystring('LoanID', '') },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        /* set value in labels */
                        $('#txtRepayment').numberbox('setValue', rec.Repayment);
                        if (rec.Freq != '' && rec.Freq != null)
                            $('#txtFreq').combobox('setValue', rec.Freq);
                        else
                            $('#txtFreq').combobox('setValue', 'Daily(Mon-Fri)');
                        if (rec.Method != '' && rec.Method != null)
                            $('#txtMethod').combobox('setValue', rec.Method);
                        else
                            $('#txtMethod').combobox('setValue', 'Simple');
                        $('#txtNextPaymentDate').datebox('setValue', formatLoanDate(rec.NextPaymentDate, null));
                        $('#txtTotalPaid').numberbox('setValue', rec.TotalPaid);
                        $('#txtContractualMaturity').datebox('setValue', formatLoanDate(rec.ContractualMaturity, null));
                        $('#txtProjectedMaturity').datebox('setValue', formatLoanDate(rec.ProjectedMaturity, null));
                        $('#txtResidual').numberbox('setValue', rec.Residual);
                        $('#txtBalance').numberbox('setValue', rec.Balance);
                        $('#txtDailyRate').numberbox('setValue', rec.DailyRate);
                        $('#lnkbtnSaveRepayment').show();
                        $('#lnkbtnAddRepayment').hide();
                    });
                }
            });

            $.ajax({
                url: '/WebServices/AM/Repayment.ashx?method=SearchArrearsByLoanID',
                contentType: 'application/json; charset=utf-8',
                data: { 'LoanID': getQuerystring('LoanID', '') },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        /* set value in labels */
                        $('#txtNumofDishonours').numberbox('setValue', rec.NumofDishonours);
                        $('#txtTotalArrears').numberbox('setValue', rec.TotalArrears);
                        $('#txtDaysOverdue').numberbox('setValue', rec.DaysOverdue);
                        $('#txtDateofDefault').datebox('setValue', formatLoanDate(rec.DateofDefault, null));
                    });
                }
            });

            $.ajax({
                url: '/WebServices/AM/Repayment.ashx?method=SearchBankDetailByLoanID',
                contentType: 'application/json; charset=utf-8',
                data: { 'LoanID': getQuerystring('LoanID', '') },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        /* set value in labels */
                        if (rec.LoanType == 'DDR BANK ACCOUNT REPAYMENT') {
                            $('#abtnEditDDRBank').linkbutton('enable');
                            $('#txtBank11').val(rec.bankname);
                            $('#txtBSB11').val(rec.bsb);
                            $('#txtAccountNo11').val(rec.accountno);
                            $('#txtAccountHolder').val(rec.HolderName);
                            $('input[name="bsb11"]').mask("999-999");
                        }
                    });
                }
            });
        }

        /*Update Repayment*/
        function SaveRepayment() {
            /*Get Text Value*/
            var AccountHolder2 = $('#txtAccountHolder').val();
            var BankName1 = $('#txtBank11').val();
            var BSB1 = $('#txtBSB11').val();
            var AccountNo1 = $('#txtAccountNo11').val();
            var Freq = $("#txtFreq").combobox('getValue');
            var Method1 = $("#txtMethod").combobox('getValue');

            /*Get Numeric Value*/
            var Repayment1 = $("#txtRepayment").numberbox('getValue');
            var TotalPaid = $("#txtTotalPaid").numberbox('getValue');
            var Residual = $("#txtResidual").numberbox('getValue');
            var Balance = $("#txtBalance").numberbox('getValue');
            var DailyRate = $("#txtDailyRate").numberbox('getValue');
            var NumofDishonours = $("#txtNumofDishonours").numberbox('getValue');
            var TotalArrears = $("#txtTotalArrears").numberbox('getValue');
            var DaysOverdue = $("#txtDaysOverdue").numberbox('getValue');

            /*Get Date Value*/
            var NextPaymentDate = $('#txtNextPaymentDate').datebox('getValue');
            if (NextPaymentDate != '')
                NextPaymentDate = DefaultformatLoanDate($('#txtNextPaymentDate').datebox('getValue'));
            var ContractualMaturity = $('#txtContractualMaturity').datebox('getValue');
            if (ContractualMaturity != '')
                ContractualMaturity = DefaultformatLoanDate($('#txtContractualMaturity').datebox('getValue'));
            var ProjectedMaturity = $('#txtProjectedMaturity').datebox('getValue');
            if (ProjectedMaturity != '')
                ProjectedMaturity = DefaultformatLoanDate($('#txtProjectedMaturity').datebox('getValue'));
            var DateofDefault = $('#txtDateofDefault').datebox('getValue');
            if (DateofDefault != '')
                DateofDefault = DefaultformatLoanDate($('#txtDateofDefault').datebox('getValue'));

            /*set value to numeric if it is blank*/
            if (Repayment1 == '')
                Repayment1 = '0.00';
            if (TotalPaid == '')
                TotalPaid = '0.00';
            if (Residual == '')
                Residual = '0.00';
            if (Balance == '')
                Balance = '0.00';
            if (DailyRate == '')
                DailyRate = '0.00';
            if (TotalPaid == '')
                TotalPaid = '0.00';
            if (TotalArrears == '')
                TotalArrears = '0.00';
            if (NumofDishonours == '')
                NumofDishonours = '0';
            if (DaysOverdue == '')
                DaysOverdue = '0';

            /*set null value to date if it is blank*/
            if (NextPaymentDate == "")
                NextPaymentDate = null;
            if (ContractualMaturity == "")
                ContractualMaturity = null;
            if (ProjectedMaturity == "")
                ProjectedMaturity = null;
            if (DateofDefault == "")
                DateofDefault = null;

            // insert record into am_repayments table for 
            $.ajax({
                url: '/WebServices/AM/Repayment.ashx?method=UpdateRepayment',
                contentType: 'application/json; charset=utf-8',
                data: { "Repayment": Repayment1, "Freq": Freq, "Method1": Method1, "NextPaymentDate": NextPaymentDate, "TotalPaid": TotalPaid, "ContractualMaturity": ContractualMaturity, "ProjectedMaturity": ProjectedMaturity, "Residual": Residual, "Balance": Balance, "DailyRate": DailyRate, 'LoanID': getQuerystring('LoanID', '') },
                success: function (data) {
                }
            });

            // insert record into am_arrears table for 
            $.ajax({
                url: '/WebServices/AM/Repayment.ashx?method=UpdateArrears',
                contentType: 'application/json; charset=utf-8',
                data: { "NumofDishonours": NumofDishonours, "TotalArrears": TotalArrears, "DaysOverdue": DaysOverdue, "DateofDefault": DateofDefault, 'LoanID': getQuerystring('LoanID', '') },
                success: function (data) {
                }
            });

            // insert record into bank details table for 
            LoanType = "DDR BANK ACCOUNT REPAYMENT";
            $.ajax({
                url: '/WebServices/AM/Repayment.ashx?method=UpdateBankInfo',
                contentType: 'application/json; charset=utf-8',
                data: { "BankName": BankName1, "AccountNo": AccountNo1, "BSB": BSB1, 'LoanID': getQuerystring('LoanID', ''), "LoanType": LoanType, "AccountHolder": AccountHolder2 },
                success: function (data) {
                    if (data == '1') {
                        alert("Save Data Successfully");
                    }
                }
            });
        }

    </script>
</body>
</html>
